<template>
  <Category />

  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <SpuList v-if="showState === 0" @setState="setState" />
    <SpuForm v-if="showState === 1" :spuInfo="spuInfo" @setState="setState" />
    <SkuForm v-if="showState === 2" :spuInfo="spuInfo" @setState="setState"/>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Spu",
});
</script>

<script setup lang="ts">
import { ref } from "vue";
import SpuForm from "./components/SpuForm/index.vue";
import SkuForm from "./components/SkuForm/index.vue";
import SpuList from "./components/SpuList/index.vue";
import type { SpuInfoType } from "@/api/spu";
import useAttrStore from "@/stores/attr";
import { storeToRefs } from "pinia";
//拿到pinia中的三级分类数据
const attrStore = useAttrStore();
const { category3Id } = storeToRefs(attrStore);

//声明一个数据,控制视图中的哪一个组件渲染
const showState = ref(0);
//保存完整的spuInfo数据,如果是新增,则把初始值传递给SpuForm组件,如果是编辑,则初始数据替换,然后传递给SpuForm组件
const spuInfo = ref<SpuInfoType>({
  category3Id: category3Id.value,
  description: "",
  spuName: "",
  tmId: null,
  spuImageList: [],
  spuSaleAttrList: [],
});

//封装一个自定义事件的回调函数,接收子组件传值,控制组件展示
const setState = (state: number, row?: SpuInfoType) => {
  showState.value = state;

  if (row) {
    //把编辑传递的Spu数据保存在初始值上
    spuInfo.value = row; //这里不需要深拷贝,因为这个组件加载的时候,上一个组件已经销毁了
  } else {
    //当用户点击的是新增过来的时候,spuInfo可能残留之前编辑传递过来的数据,所以我们要再次初始化spuInfo
    spuInfo.value = {
      category3Id: category3Id.value,
      description: "",
      spuName: "",
      tmId: null,
      spuImageList: [],
      spuSaleAttrList: [],
    };
  }
};
</script>
